package com.cxs.xiaomi.web.controller;

import com.cxs.xiaomi.domain.User;
import com.cxs.xiaomi.service.UserService;
import com.cxs.xiaomi.service.impl.UserServiceImpl;
import com.cxs.xiaomi.utils.*;
import cxs.utils.servlet.exception.ParamMapException;
import cxs.utils.servlet.exception.ParamValueException;
import cxs.utils.utils.ParamsAsBean;
import cxs.utils.utils.Result;


import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 * @Author:cxs
 * @Date:2021/9/14  16:13
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@WebServlet(name = "UserServlet", urlPatterns = "/userservlet")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    public Object checkUserName(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        if (StringUtil.empty(username)) {
            return new Result<String>("用户名为空", 201, null);
        }
        if (userService.checkUsernameExist(username.trim())) {
            return Result.OK("用户名已存在", 201, null);
        } else {
            return Result.OK("校验通过", 200, null);
        }
    }

    // 验证码
    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获得验证码并存入session
        BufferedImage image = ValidateCodeUtil.getCodeImage(request.getSession(), "vcode", 4);
        // 给客户端
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    // 校验验证码
    public Object checkCode(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String vcode = (String) session.getAttribute("vcode");
        String code = request.getParameter("code");
        if (StringUtil.empty(code)) {
            return Result.failare("验证码不能为空");
        }
        if (vcode.equalsIgnoreCase(code)) {
            return Result.OK("验证码正确", 200, null);
        } else {
            return Result.OK("验证码有误,请重新输入", 201, null);
        }
    }


    // 登录
    public Object login(HttpServletRequest request, HttpServletResponse response) {
        String auto = request.getParameter("auto");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");
        if (StringUtil.empty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "forward:/login.jsp";
        }
        if (StringUtil.empty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "forward:/login.jsp";
        }
        if (StringUtil.empty(vcode)) {
            request.setAttribute("msg", "验证码不能为空");
            return "forward:/login.jsp";
        }
        User user = userService.login(username, MD5Util.getStringMD5(password.trim()));
        if (user != null) {
            if (user.getFlag() == 0) {
                request.setAttribute("msg", "用户:" + username + " 未激活");
                return "forward:/login.jsp";
            }
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            if (auto != null) {
                DatabackUtil.dataReback(request);
                try {
                    Cookie loginCookie = new Cookie("loginCookie", URLEncoder.encode("login_time_" + user.getId() + ":" + System.currentTimeMillis(), "utf-8"));
                    loginCookie.setPath(request.getContextPath());
                    loginCookie.setMaxAge(60 * 60 * 24 * 14);
                    loginCookie.setHttpOnly(true);
                    response.addCookie(loginCookie);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return "redirect:/index.jsp";
        }
        request.setAttribute("msg", "用户名或密码错误");
        return "forward:/login.jsp";
    }

    // 注册
    public Object register(HttpServletRequest request, HttpServletResponse response) {
        try {
            User user = ParamsAsBean.parammeterAsBean(User.class, request, true);
            System.out.println(user);
            if (user != null) {
                if (userService.register(user)) {
                    return "redirect:/registerSuccess.jsp";
                }
                return "redirect:/register.jsp";
            }
        } catch (ParamMapException e) {
            e.printStackTrace();
        } catch (ParamValueException e) {
            e.printStackTrace();
            request.setAttribute("registerMsg", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "forward:/register.jsp";
    }

    // 激活账号
    public String active(HttpServletRequest request, HttpServletResponse response) {
        String email = request.getParameter("e");
        String code = request.getParameter("c");
        try {
            if (StringUtil.empty(email) || StringUtil.empty(code)) {
                request.setAttribute("msg","非法请求,请勿篡改");
                return "forward:/message.jsp";
            }
            if (userService.activeCount(email, code)) {
                request.setAttribute("msg","激活成功");
                return "forward:/message.jsp";
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg",e.getMessage());
            return "forward:/message.jsp";
        }
        request.setAttribute("msg","激活失败,请重试");
        return "forward:/message.jsp";
    }

    public String logOut(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            session.removeAttribute("user");
            session.invalidate();
        }
        // 清除cookie
        Cookie loginCookie = new Cookie("loginCookie", null);
        loginCookie.setPath(request.getContextPath());
        loginCookie.setMaxAge(0);
        response.addCookie(loginCookie);
        return "redirect:/login.jsp";
    }


    // 管理员
    // 获得用户信息
    public Object getUserList(HttpServletRequest request, HttpServletResponse response){
        List<User> list = userService.userList();
        return Result.OK("操作成功",list);
    }

    // 删除用户
    public Object deleteUser(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        if(StringUtil.empty(id)){
            return Result.failare("id不能为空");
        }
        return userService.del(Integer.parseInt(id.trim())) ?
                Result.OK("删除成功") :
                Result.failare("删除失败");
    }
    // 条件查询用户
    public Object searchUser(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        StringBuilder sb = new StringBuilder();
        List params = new ArrayList();
        sb.append(" where 1=1 ");
        if(!StringUtil.empty(username)){
            sb.append("and username like ? ");
            params.add("%" + username.trim() + "%");
        }
        if(!StringUtil.empty(gender)){
            sb.append(" and gender = ?");
            params.add(gender.trim());
        }
        List<User> userList = userService.likeSearch(sb.toString(),params);
        return Result.OK("操作成功",userList);
    }

    // 测试
    public void test(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("测试方法执行");
    }
}
